package cn.com.taiji.oospub.wechat.controller.member;


import cn.com.taiji.manager.ManagerException;
import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.controller.WXBaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.*;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.com.taiji.oospub.wechat.common.wxpay.pay.Configure.requestGetMemberInfo;

@Controller
@RequestMapping("/wx")
public class MemberInfoController extends WXBaseLogController {

    @Autowired
    private IMemberBaseInfoService memberBaseInfoManager;
    @Autowired
    private IMemberWeightService memberWeightManager;
    @Autowired
    private IMemberBmiService coursesBmiService;
    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsService;
    @Autowired
    private ISnsuserinfoService snsuserinfoService;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private IAccesstokensaveService accesstokensaveService;
    @Autowired
    private IMemberAllowanceUseHistoryService memberAllowanceUseHistoryService;
    @Autowired
    private ICustomerMinMumService customerMinMumService;


    @Value("${kongxc_pos_http_server_url}")
    private String kongxc_pos_http_server_url;
    @Value("${chuzhika_num}")
    private String chuzhika_num;
    @Value("${chuzhika_faFang}")
    private String chuzhika_faFang;

    @Value("${PROPASS}")
    public String PROPASS;
    @Value("${PROJECT_CODE}")
    public String PROJECT_CODE;
    @Value("${CUS_NAME}")
    public String CUS_NAME;


    //----------保存个人健康信息-----------
    @RequestMapping(value = "/memberInfo/healthAdd", method = RequestMethod.POST)
    public void healthAdd(@RequestBody MemberBaseInfo entity, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            MemberBaseInfo memberBaseInfo = memberBaseInfoManager.getById(entity.getId());
            memberBaseInfo.setActive(entity.getActive());
            memberBaseInfo.setUserAge(entity.getUserAge());
            memberBaseInfo.setHeight(entity.getHeight());
            memberBaseInfo.setAimWeigth(entity.getAimWeigth());
            memberBaseInfo.setSchoolId(memberBaseInfo.getSchoolId());
            if (!entity.getWeightId().equals(memberBaseInfo.getWeightId())) {
                memberBaseInfo.setWeightId(entity.getWeightId());
                MemberWeight weightInfo = new MemberWeight();
                weightInfo.setCreateTime(LocalDateTime.now());
                weightInfo.setWeight(entity.getWeightId());
                weightInfo.setCreator(memberBaseInfo.getId());
                memberWeightManager.save(weightInfo);
            }
            memberBaseInfo.setWeightId(entity.getWeightId());
            memberBaseInfoManager.updateById(memberBaseInfo);
            MemberBmi memberBmi = new MemberBmi();
            memberBmi.setBmi(entity.getBmi());
            memberBmi.setMemberId(memberBaseInfo.getId());
            memberBmi.setCreatTime(LocalDateTime.now());
            coursesBmiService.save(memberBmi);

            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, memberBaseInfo);
            writeSuccessToBrowers("个人健康信息修改成功", response);
        } catch (Exception e) {
            e.printStackTrace();
            writeFailToBrowers(e.getMessage(), response);
        }
    }


    //获取个人信息
    @RequestMapping(value = "/memberInfo/getPersonInfo", method = RequestMethod.GET)
    @ResponseBody
    public String infoGet(Model model, HttpServletRequest request) {
        MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        MemberBaseInfo oldInfo = memberBaseInfoManager.findById(memInfo.getId());
        List<MemberBmi> memberBmiList = coursesBmiService.getByMemberId(oldInfo.getId());
        if (memberBmiList != null && memberBmiList.size() > 0) {
            oldInfo.setBmi(memberBmiList.get(0).getBmi());
        }
        model.addAttribute("memInfo", oldInfo);
        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        model.addAttribute("activity", MemberBaseInfo.Active.values());
        return JSONObject.toJSONString(model);
    }

    //修改页面语言
    @RequestMapping(value = "/memberInfo/changeLanguage", method = RequestMethod.GET)
    @ResponseBody
    public String changeLanguageGet(Model model, HttpServletRequest request) {
        MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        model.addAttribute("memInfo", memInfo);
        model.addAttribute("zhOrEn", JSONObject.toJSONString(Finals.ZhOrEn.values()));
        return JSONObject.toJSONString(model);
    }

    //更新用户个人信息
    @RequestMapping(value = "/memberInfo/updateInfo", method = RequestMethod.POST)
    public void infoPost(@RequestBody MemberBaseInfo entity, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            MemberBaseInfo oldInfo = memberBaseInfoManager.findById(entity.getId());
            oldInfo.setEmail(entity.getEmail());
            oldInfo.setName(entity.getName());
            oldInfo.setMale(entity.getMale());
            oldInfo.setZhOrEn(entity.getZhOrEn());
            if (!oldInfo.getMobile().equals(entity.getMobile())) {
                MemberBaseInfo info = memberBaseInfoManager.findByPhone(entity.getMobile());
                if (info != null && !info.getId().equals(oldInfo.getId())) {
                    throw new ManagerException("你输入的手机号已被关联用户");
                } else {
                    oldInfo.setMobile(entity.getMobile());
                }
            }
            memberBaseInfoManager.updateById(oldInfo);
            WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, memberBaseInfoManager.findById(entity.getId()));
            super.addLoginLog(request, "个人信息修改({})成功", oldInfo.getLoginName());
            writeSuccessToBrowers("个人信息修改成功", response);
        } catch (Exception e) {
            writeFailToBrowers(e.getMessage(), response);
        }
    }

    //月度报告
    @RequestMapping(value = "/memberInfo/monthlyReport", method = RequestMethod.GET)
    public void monthlyReport(Model model, HttpServletRequest request, HttpServletResponse response) {
        String openId = request.getParameter("openId");
        MemberBaseInfo loginUser = memberBaseInfoManager.findByProperty("openId", openId);
        this.coursesOrdersDetailsService.exportExcelDetail(loginUser, response);
    }


    //个人信息主页(查询微信头像)
    @RequestMapping(value = "/memberInfo/getUserHeadImg", method = RequestMethod.POST)
    @ResponseBody
    public String infoPost(HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        Snsuserinfo wxUser = snsuserinfoService.findByProperty("openId", memInfo.getOpenid());
        if (wxUser != null) {
            memInfo.setHeadImg(wxUser.getHeadImgUrl());
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("headImg", "name", "Email", "idNumber");
        return JSONObject.toJSONString(memInfo, filter);
    }

    //查看用户是否关注公众号
    @GetMapping(value = "/memberInfo/isFocusOn")
    @ResponseBody
    public String isFocusOn(Map<String, Object> map, HttpServletRequest request) {
        MemberBaseInfo memInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        Accesstokensave accesstokensave = accesstokensaveService.query().one();
        map.put("isFocusOn", false);
        assert memInfo != null;
        String url = requestGetMemberInfo.replace("OPENID", memInfo.getOpenid()).replace("ACCESS_TOKEN", accesstokensave.getAccessToken());
        JSONObject result = JSONObject.parseObject(HttpUtil.get(url));
        if (result != null) {
            if ("1".equals(result.getString("subscribe"))) {
                //已关注
                map.put("isFocusOn", true);
            }
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("isFocusOn");
        return JSONObject.toJSONString(map, filter);
    }


    @PostMapping(value = "/memberInfo/addDiscountHistory")
    @ResponseBody
    public String addDiscountHistory(@RequestBody MemberAllowanceUseHistory memberAllowanceUseHistory) {
        Map<String, Object> map = new HashMap<>();
        MemberBaseInfo memberBaseInfo = memberBaseInfoManager.findByProperty("Id_Number", memberAllowanceUseHistory.getCustomerNo());
        if (memberBaseInfo == null) {
            map.put("result", "fail");
            map.put("message", "未查询到顾客");
        } else {
            memberAllowanceUseHistory.setCreateTime(LocalDateTime.now());
            memberAllowanceUseHistory.setMemberId(memberBaseInfo.getId());
            if (memberAllowanceUseHistoryService.save(memberAllowanceUseHistory)) {
                map.put("result", "success");
            } else {
                map.put("result", "fail");
            }
        }
        return JSONObject.toJSONString(map);
    }


}
